package com.txsj.scan.utils;

import android.util.Log;

import com.google.gson.Gson;
import com.greendao.GoodsInfoDao;
import com.txsj.scan.bean.BaseListResult;
import com.txsj.scan.bean.EpcInfo;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.http.ApiServer;
import com.txsj.scan.http.requestframework.RetrofitManager;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class GZIPUtils {
    public static final String GZIP_ENCODE_UTF_8 = "UTF-8";
    public static final String GZIP_ENCODE_ISO_8859_1 = "ISO-8859-1";

    /**
     * 字符串压缩为GZIP字节数组
     * @param str
     * @param encoding
     * @return
     */
    public static byte[] compress(String str, String encoding) {
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(encoding));
            gzip.close();
        } catch (IOException e) {
            Log.e("gzip compress error.", e.getMessage());
        }
        return out.toByteArray();
    }

    /**
     * Gzip  byte[] 解压成字符串
     * @param bytes
     * @return
     */
    public static String uncompressToString(byte[] bytes) {
        return uncompressToString(bytes, GZIP_ENCODE_UTF_8);
    }


    /**
     * Gzip  byte[] 解压成字符串
     * @param bytes
     * @param encoding
     * @return
     */
    public static String uncompressToString(byte[] bytes, String encoding) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        try {
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString(encoding);
        } catch (IOException e) {
            Log.e("gzip compress error.",e.getMessage());
        }
        return null;
    }

    /**
     * 判断byte[]是否是Gzip格式
     * @param data
     * @return
     */
    public static boolean isGzip(byte[] data) {
        int header = (int)((data[0]<<8) | data[1]&0xFF);
        return header == 0x1f8b;
    }


    public static void main(String[] args) throws IOException {
        String s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        String test = "H4sIAAAAAAAEAF2PywrDIBBF/2XWLtTE1PgrpYgvkkCIMI50EfLvFVModHmGe2bunFBqCKkUMIQ1MQi5HgRmEGp4aAbRkQPzPIHcYrcIhjPw6I7YQTJYco7lBqmb4B2FtbPgQkuumxAqYjrIlrTv9u0wrbmW9A3xQcm/yO/AOGslZwa7K2T91qY90GzsVTLGhHev68WA2htCjartFGqSE78+btPDfOAAAAA=";
        s= test;

       int a = 5<<2;
       int b = 5>>2;
       int c = -5>>2;
       int d = -5<<2;
       int e = -5>>>2;//无符号右移
       int f = 5>>>2;//无符号右移

//        System.out.println("字符串长度：" + s.length());
//        System.out.println("压缩后：：" + compress(s).length);
//        System.out.println("解压后：" + uncompress(compress(s)).length);
//        System.out.println("解压字符串后：：" + uncompressToString(compress(s)).length());

//        byte[] result = Base64.getEncoder().encode(s.getBytes());


//        System.out.println(s);
//        System.out.println(GZIPUtils.uncompressToString(Base64.decode(s),GZIP_ENCODE_UTF_8));

//        getEpcRetrofitHttp();

//        testHttp();

//        chaiZhuangXiang();

//        weiYunSuan();


//        System.out.println("result="+fun("Smart"));

//        System.out.print(-5<<2);

        cancelJiaMi();
    }

    public static String fun(String s){
        return s.length()<0?(fun(s.substring(1)+s.charAt(0))):"";
    }

    //位运算符
    private static void weiYunSuan() {
        int a= 2;
        int result = a++ + 4<<2;
        System.out.println(result);
        System.out.println(4<<2);
    }

    //拆装箱
    private static void chaiZhuangXiang() {
        Integer a = 123456;
        Integer b = 123456;
        System.out.println(a == b);
        a = a;
        b = 1;
        System.out.println(a == b);
    }

    public static void getCount(){
        List<GoodsInfo> list = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().loadAll();

        List<GoodsInfo> list1 = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().queryBuilder()
                .where(GoodsInfoDao.Properties.Warehouse_id.eq(100492)
                )
                .list();
        List<GoodsInfo> list2 = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().queryBuilder()
                .where( GoodsInfoDao.Properties.Warehouse_id.eq(100145)
                )
                .list();
        List<GoodsInfo> list3 = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().queryBuilder()
                .where(GoodsInfoDao.Properties.Warehouse_id.eq(100144)
                )
                .list();
        List<GoodsInfo> list4 = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().queryBuilder()
                .where(GoodsInfoDao.Properties.Warehouse_id.eq(100146)
                )
                .list();
        Trace.e("goodsInfo商品总数:"+list.size());
        Trace.e("goodsInfo商品总数1:"+list1.size());
        Trace.e("goodsInfo商品总数2:"+list2.size());
        Trace.e("goodsInfo商品总数3:"+list3.size());
        Trace.e("goodsInfo商品总数4:"+list4.size());
    }

    public static void testHttp() {
        Map<String,String> params = RetrofitManager.getParams();
        RetrofitManager.getDefault().create(ApiServer.class).test(RetrofitManager.getHeader(),params)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            Trace.e(response.body().source().readByteArray().length+"");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Trace.e(t.getMessage());
                    }
                });


    }

    private static int tagPageIndex=0;
    private static int currentRetryLabelCount = 0;//标签的
    // 可重试次数
    private static int maxConnectCount = 20;
    private static int waitRetryLabelTime = 0;
    /**
     * 获取标签数据
     * 韩断线重连机制
     */
    public static void getEpcRetrofitHttp() {
        Map<String, String> params = RetrofitManager.getParams();
        params.put("brandid", PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID,""));
        params.put("select_brand", PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID,""));
        params.put("page_index", tagPageIndex + "");
        params.put("page_size", "10000");
        Map<String,String> header = RetrofitManager.getHeader();
        header.put("gzip_type","1");
        RetrofitManager.getDefault().create(ApiServer.class).getEpcByteListUrl(header, params)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            //获得response中的body的字节数组
                            byte[] data = response.body().bytes();
                            //通过UTF-8解压缩成json字符串
                            String json = uncompressToString(data,GZIP_ENCODE_UTF_8);
                            //将字符串转换成定义好的数据类型
                            BaseListResult<EpcInfo> result = new Gson().fromJson(json,BaseListResult.class);
                            //获取标签列表
                            List<EpcInfo> list = result.getData();
                            Trace.e("返回的标签集合"+list.size());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Trace.e(t.getMessage());
                    }
                });


    }

    public static void cancelJiaMi(){
        String path = "https://open.ys7.com/api/lapp/device/encrypt/off";
        Map<String, String> params = new HashMap<>();
        params.put("accessToken", "at.8ltirupkc11lit56aa7x6u499qe8kpdj-45ff9wm00h-02ry33h-7zxdozf19");
        params.put("deviceSerial", "C04104941");
        params.put("validateCode", "MAIKE100");
        RetrofitManager.getDefault().create(ApiServer.class).encryptDevice(path,params)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Trace.e("wcj请求结果:"+response.body());
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Trace.e("wcj请求结果:"+t.getMessage());
                    }
                });


    }
}
